<?php

class UserController extends HBaseController
{
	public $layout="//layouts/home_mini_foot";

	/**
	 * 登录
	 */
	public function actionLogin()
	{
		$model=new LoginForm;
        
		//判断是否未登录
		if(!Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->user->returnUrl);
		}
		
//		 异步验证
// 		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
// 		{
// 			echo CActiveForm::validate($model);
// 			Yii::app()->end();
// 		}
				
//		自动登录
//		if(Yii::app()->user->allowAutoLogin){
//			$key =  Yii::app()->user->getStateKeyPrefix();
//			$cookies = Yii::app()->request->cookies;
//			$userCookie = Yii::app()->securityManager->validateData($cookies[$key]);
//			$userCookie = $userCookie ? unserialize($userCookie) : '';
//			if($userCookie && $userCookie[3]['expire']>time()){
//				Member::model()->setUserInfo($userCookie[1]);
//				$this->redirect(Yii::app()->user->returnUrl);
//			}
//		}

		if(isset($_POST['LoginForm'])){
			//IP检查
			if(!Ipbanned::model()->ipCheck()){
				header("Content-type:text/html;charset=utf-8");
				Message( t('IP Error') );
			}
			
			//收集登录表单进行验证，成功登录后更新相关信息
			$model->attributes=$_POST['LoginForm'];
			$member = Member::model()->loadModelByfield('zm_name',$model->zm_name);


			//判断会员是否激活注册
			$email = $member->zm_email; 
			if($member->zm_check_status==1&&$model->validate()&&$email==0){
				$this->redirect(array('registertwo','id'=>$member->zm_id));
				exit;
			}
			else if($member->zm_check_status==1&&$model->validate()){
			$this->render('registerthree',array('model'=>$member));
				exit;
			}
			if($model->validate() && $model->login()){
				
				$usertype = isset(Yii::app()->user->usertype) ? Yii::app()->user->usertype : '';
				if($usertype == 'member'){
					$member = Member::model()->loadModelByfield('zm_name',$model->zm_name);
					if(empty($member))//手机登录
						$member = Member::model()->findByAttributes(array('zm_mob' => $model->zm_name));
					if(empty($member))//邮箱登录
						$member = Member::model()->findByAttributes(array('zm_email' => $model->zm_name));
					$member->setUserInfo();
					//设置此次登录相关信息到模型中
					$member->zm_today_time = date('Ymd',$member->zm_last_time) == date('Ymd',time()) ? new CDbExpression('zm_today_time+1') : 1 ;
					$member->zm_last_time = time();
					$member->zm_total_time = new CDbExpression('zm_total_time+1');
					$member->zm_ip = Yii::app()->request->userHostAddress;
										
					//保存登录相关信息
					$member->update(
						array(
							'zm_today_time', 
							'zm_last_time', 
							'zm_total_time', 
							'zm_ip',
						)
					);					
				}else{
					$member = MemSub::model()->findByAttributes(array('zms_username' => Yii::app()->user->subname));
					$member->setUserInfo();
				}
				//返回上一页地址
				if($_POST['returnUrl']){
					$url = $_POST['returnUrl'];
				}else{
					$url = Yii::app()->user->returnUrl;
				}
				$this->redirect($url);
			}else{
				//写入错误提示
				$msg = t('Password Error');				
				setFlash($msg);
				$this->render('login',array('model'=>$model));				
				exit;
			}
		}
		//读取记录在客户端的帐号密码
		$cookies = Yii::app()->request->cookies;
		if(isset($cookies['loginInfo']) && $cookies['loginInfo']){
			$loginInfo = Yii::app()->securityManager->validateData($cookies['loginInfo']->value);
			if($loginInfo){
				$loginInfo = unserialize(Yii::app()->securityManager->decrypt($loginInfo));
				$model->attributes = $loginInfo;
				$model->rememberMe = 1;				
			}
		}		
		$this->render('login',array('model'=>$model));
	}
	
	//退出
	public function actionLogout()
	{
		if(isset(Yii::app()->request->cookies['loginInfo'])){
			unset(Yii::app()->request->cookies['loginInfo']);
			//print_r(Yii::app()->securityManager->decrypt(Yii::app()->request->cookies['loginInfo']));exit;
		}
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
		
	}
	
	//外部action
	public function actions()
	{
		return array(
			//验证码
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
				'minLength'=>4,  //最短为4位
				'maxLength'=>4,   //是长为4位
				'height'=>'35',
				'width'=>'100',
				'padding'=>'0',
				'testLimit'=>999,    //这里可以设置大一些,以免验证超过三次会出错.
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	//注册1
	function actionRegisterOne(){
		$model=new Member('register');
		$this->render('register',array('model'=>$model));
	}
	
	//注册2
	function actionRegisterTwo(){
		$model=new Member;
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form'){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		$model=new Member('user-form');
		if(isset($_POST['Member']))
		{
			$model->attributes=$_POST['Member'];
			if(!$model->validate()){
				$message = $model->getErrorsStr();
				echo $message;exit;
			}
			$model->zm_paypsword = $model->passwordEncode($model->zm_psword , 2);
			$model->zm_psword = $model->passwordEncode($model->zm_psword);
			$model->zm_code = $model->zm_code;
			$model->zm_reg_ip = Yii::app()->request->userHostAddress;
			$model->zm_today_time = 0;
			$model->zm_total_time = 0;
			$model->zm_status = 2;
			$model->updatetime = $model->inputtime = time();
			$model->zm_email = 0;
			$model->save(false);
			
			//会员默认等级，读取配置
			$params = Yii::app()->filecache->get('setting');
			//print_r($params);exit;
			$glog = new MemGlog();
			$glog->userid   = $model->zm_id;
			$glog->itemname = $params['defaultLevel'];
			$glog->inputtime = time();
			$glog->save();

			//写入会员附加信息表
			$mempro = new MemPro();
			$mempro->zm_id   = $model->zm_id;
			$mempro->zmp_nickname = $model->zm_name;
			$mempro->zmp_lastname = $model->zm_name;
			$mempro->zmp_qq       = 1000000;
			$mempro->zar_id       = 524 ;
			$mempro->zmp_address  = '广东深圳' ;
			$mempro->save();
		}
		if(isset($_GET['id'])){
			$model = Member::model()->findByPk($_GET['id']);
		}
		if(empty($model->zm_id))
			Message( t('Error') );
		
		$this->render('registertwo',array('model'=>$model));
		Yii::app()->end();
	}
	
	//注册3
	public function actionRegisterThree()
	{

		$model=new Member;
		$model->scenario = 'register';
		if(isset($_POST['ajax']) && $_POST['ajax']==='register'){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		if(isset($_POST['Member']['zm_email']) && isset($_POST['Member']['zm_name']))
		{ 
			$model->attributes = $_POST['Member'];
			$exists = $model->exists('zm_email=:zm_email',array(':zm_email'=>$model->zm_email));
			if( !$exists ){
				$up=Yii::app()->db->createCommand('update {{member}} set zm_email=\''.$_POST['Member']['zm_email'].'\' where zm_name=\''.$_POST['Member']['zm_name'].'\'');
				$up->execute();
				
				//发送激活邮件....
				$url = $model->createActivateUrl();
				$mailer = Yii::app()->mailer;
				if(Yii::app()->params['mailType'] == 'smtp'){					
					$mailer->IsSMTP();
					$mailer->SMTPAuth = true;
				}
				$mailer->AddReplyTo($model->zm_email);
				$mailer->AddAddress($model->zm_email);
				$mailer->Subject = '用户邮箱激活';
				$params = array('username'=>$model->zm_name,'url'=>$url);
				$mailer->getView('activate', array('params'=>$params,'mailer'=>$mailer),'member');
				if(!$mailer->Send()){
					Message( t('Send Mail Error') );
				}
				setFlash(t('Send Activate Email')) ;
				$this->render('registerthree',array('model'=>$model));
				//$this->redirect(Yii::app()->createUrl('home/user/login'));
			}else{
				//Yii::app()->user->setFlash('email_return',t('Emal Repeat'));
 				$this->render('registertwo',array('model'=>$model));				
			}
		}else{
			Message( t('Error') );
		}
	}


	//重新发送Email
	public function actionAgainEmail(){
		$model=new Member('registertwo');
		$model->attributes = $_POST['Member'];
		//发送激活邮件....
		$url = $model->createActivateUrl();
		$mailer = Yii::app()->mailer;
		if(Yii::app()->params['mailType'] == 'smtp'){					
			$mailer->IsSMTP();
			$mailer->SMTPAuth = true;
		}
		$mailer->AddReplyTo($model->zm_email);
		$mailer->AddAddress($model->zm_email);
		$mailer->Subject = '用户邮箱激活';
		$params = array('username'=>$model->zm_name,'url'=>$url);
		$mailer->getView('activate', array('params'=>$params,'mailer'=>$mailer),'member');
		if(!$mailer->Send()){			
			Message( t('Send Mail Error') );
		}
		setFlash(t('Send Activate Email')) ;
		$this->render('registerthree',array('model'=>$model));
	}


	//激活邮箱
	public function actionActivateEmail(){
		$model = Member::model();
		$params = $model->getEmailParams();
		$conditions = "zm_id='{$params['zm_id']}' and zm_email='{$params['zm_email']}' and zm_code='{$params['zm_code']}'";
		$record = $model->find($conditions);
		if($record){
			$record->zm_check_status = $record->zm_check_status == 1 || $record->zm_check_status == 2 ? 2 : 4;
			header("Content-type:text/html;charset=utf-8");
			if($record->update()){
				//Message( t('Email Activate Success') );
				$this->render('registerfour');
			}else{
				Message( t('Activate Error') );
			}
		}else{
			Message( t('Anew Activate Link') );
		}
	}
	
	//找回密码1
	function actionGetPass(){
		$model=new Member('getpass');
		$this->render('getpass',array('model'=>$model));
	}
	
	//找回密码2
	function actionGetPassTwo(){
		$model=new Member;
		if(isset($_POST['ajax']) && $_POST['ajax']==='getpass-form'){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		$model=new Member('getpass');
		if(isset($_POST['Member']))
		{
			$model->attributes=$_POST['Member'];
			if(!$model->validate()){
				$message = $model->getErrorsStr();
				echo $message;exit;
			}
		
		}
		if(isset($_POST['zm_email']) && !empty($_POST['zm_email']) && isset($_POST['zm_name']) && !empty($_POST['zm_name'])){
			$record = Member::model()->getFieldsByName($_POST['zm_name'] , 'zm_id,zm_name,zm_email,zm_code');
			if(!$record || $record->zm_email !=$_POST['zm_email'] ){
				Message( t('Error') );
			} 
			//发送邮件....
			//mail("526777655@qq.com","My subject",'mycontent');exit;
			$hashArr = array(
						'zm_id'   =>$record->zm_id,
						'zm_code' =>$record->zm_code,
						'zm_email'=>$record->zm_email,
						'time'    => time()+3600*24*3
					);
			$hash = Tool::encryptParamsForUrl($hashArr);
			$url = Yii::app()->urlManager->createUrl('home/user/getpassthree',array('hash'=>$hash));
			$url = Yii::app()->homeUrl.$url;
			$mailer = Yii::app()->mailer;
			if(Yii::app()->params['mailType'] == 'smtp'){					
				$mailer->IsSMTP();
				$mailer->SMTPAuth = true;
			}
			$mailer->AddReplyTo($record->zm_email);
			$mailer->AddAddress($record->zm_email);
			$mailer->Subject = '找回登录密码-来自'.app()->name;
			$params = array('username'=>$record->zm_name,'url'=>$url);
			$mailer->getView('getpass', array('params'=>$params,'mailer'=>$mailer),'member');
			if($mailer->Send()){
				$this->render('getpasstwo');
			}
		}elseif( isset($_POST['zm_email']) && !empty($_POST['zm_email']) ){
			$record = Member::model()->loadModelByfield('zm_email' , $_POST['zm_email']);
			if(!$record){				
                Message( t('Error Email') );  
        		exit;				
			}
			$this->render('getpasstwo',array('model'=>$record));
			Yii::app()->end();
		}else{
			Message( t('Error') );
		}
	}

	//找回密码3
	function actionGetPassThree(){
		$hash = Yii::app()->request->getParam('hash');
		if(!$hash){						
			Message( t('Error Apply Pass') );
		}
		$params = Tool::decryptParamsForUrl($hash);
		if(count($params)<4){
			Message( t('Error Apply Pass') );
		}elseif( time() > $params['time'] ){
			Message( t('Apply Pass Time Error') );			
		}
		$conditions = 'zm_id=:zm_id and zm_email=:zm_email and zm_code=:zm_code';
		$findParams = array(
					':zm_id'=>$params['zm_id'],
					':zm_email'=>$params['zm_email'],
					':zm_code'=>$params['zm_code'],
				);
		$record = Member::model()->find($conditions,$findParams);
		if(!$record){
			Message( t('Error Apply Pass') );
		}
		$record->formHash = md5($record->zm_psword.$record->zm_code);
		$this->render('getpassthree',array('model'=>$record));
	}

	//找回密码4
	function actionGetPassFour(){
		$type = $_POST['Member']['type'];
		$field = 'zm_'.$type;
		$code = $type=='psword' ? 1 : 2; //$code：加密解密识别码，1为登录密码，2为支付密码
			
		if( $_POST['Member']['zm_'.$type] != $_POST['Member']['re_'.$type] || empty($_POST['Member']['zm_'.$type])){
			Message( t('Confirm Password Error') );			
		}
		$model = Member::model()->findByPk($_POST['Member']['zm_id']);
		//print_r($model);exit;		
		if( $_POST['Member']['formHash']!==md5($model->zm_psword.$model->zm_code) ){
			Message( t('Error') );	
		}
		$model->$field = $model->passwordEncode( $_POST['Member'][$field] , $code );
		if($model->save(false)){
			//修改成功
			$this->render('getpassfour');
		}else{
			//修改失败
			Message( t('Failed') );
		}
	}

	//邮件激活，修改邮箱，
	public function actionChangeMail(){
		//解析参数
		$params = Member::model()->getEmailParams();
		
		$record = Member::model()->findByPk($params['zm_id']);
		if($record){
			$record->zm_email = $params['zm_email'];
			header("Content-type:text/html;charset=utf-8");
			//验证缓存随机码
			$cachecode = Yii::app()->filecache->get($record->zm_id.'-mailCacheCode');
			if($cachecode==$params['zm_code']){
				if($record->update()){
					Yii::app()->filecache->delete($record->zm_id.'-mailCacheCode');
					Message( t('Email Modify Success') );
				}else{
					Message( t('Activate Error') );
				}
			}else{
				Message( t('Activate Link Error') );				
			}
		}else{
			Message( t('Anew Activate Link') );			
		}
	}
	
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
	
	//判断注册用户名是否存在
	public function actionAjaxCheckUserName(){

			$name = $_GET['Member']['zm_name'];
			$criteria=new CDbCriteria;
			$criteria->compare('zm_name',trim(strtolower($name)));
			if(Member::model()->exists($criteria)){
				echo 0;//校验不能过返回0
			}else{
				echo 1;//校验通过返回1
			}
			exit;
			
	}
	
}